package com.link.base.base.servicerequest.service;

import com.link.base.base.servicerequest.model.ServiceRequest;
import com.link.core.cllog.LCLogger;
import com.link.base.base.servicerequest.dao.mybatis.mapper.AcceptanceMapper;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.StringUtils;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author unknown
 * @date unknown
 */
@Service
public class AcceptanceServiceImpl extends BasicServiceImpl<ServiceRequest> implements AcceptanceService {

    @Resource
    private AcceptanceMapper acceptanceMapper;

    @Override
    public BasicMapper<ServiceRequest> getBasicMapper() {
        return acceptanceMapper;
    }

    /**
     * <p>插入数据前校验</p>
     *
     * @author yrf
     * @param entity
     */
    @Override
    public void beforInsert(ServiceRequest entity) {
        String errorMsg = validate(entity);
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new ServiceException(errorMsg);
        }
    }

    @Override
    public void beforUpdate(ServiceRequest entity) {
        String errorMsg = validate(entity);
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new ServiceException(errorMsg);
        }
    }

    /**
     * 数据校验(合同号)
     *
     * @param entity
     * @return 如果不通过则返回错误信息，否则返回 null
     */
    private String validate(ServiceRequest entity) {
        String result = null;
        QueryParams entityParam = null;
        String validate = "";
        try {
            validate = entity.getContractCode();
            if (StringUtils.isNull(validate)) {
                throw new ServiceException("SERVICEREQUEST-001");
            }
            entityParam = new QueryParams();
            entityParam.setPage(1);
            entityParam.setRows(1);
            entityParam.setPageFlag(false);
            entityParam.addFilter(new Filter("contractCode", validate));
            if (null != entity.getId()) {
                entityParam.addFilter(new Filter("id", Filter.OP_NOT_EQUAL, entity.getId().toString()));
            }
            ServiceRequest queryObj = new ServiceRequest();
            queryObj.setPageFlag(false);
            queryObj = (ServiceRequest) ServiceRequest.transformClass(ServiceRequest.class, entityParam);

            List<ServiceRequest> entityList = queryByExamplePage(queryObj);
            if (entityList.size() > 0) {
                throw new ServiceException("SERVICEREQUEST-002");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result = e.getMessage();
        }
        return result;
    }
}
